<template>
  <div id="app">
    <div class="header">
      <el-button @click="dialogFormVisible  = true">添加</el-button>
          <el-upload
              action=""
              :on-change="onChange"
              :auto-upload="false"
              :show-file-list="false"
              accept=".xls, .xlsx"
            >
              <el-button type="warning" icon="el-icon-folder-add">批量导入</el-button>
            </el-upload>
            <el-button type="warning" icon="el-icon-download" @click="exportToExcel">批量导出</el-button>
    </div>

    <div class="container">
          <el-table
          border
    :data="listdata"
    style="width: 100%">
    <el-table-column
      v-for="item in keylist" 
      :key='item'
      :prop="item"
      :label="item"
      width="180"
      >
    </el-table-column>
    <el-table-column label="操作" >
      <template slot-scope="scope" v-if='scope.row'> 
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[2,5,10,15]"
      :page-size="page"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </div>
    
     <!-- 添加一条 -->
 <el-dialog title="添加一条" :visible.sync="dialogFormVisible">
  <el-form>
    <el-form-item v-for='item in this.keylist' :key='item' :label="item" :label-width="formLabelWidth">
      <el-input  v-model="form[item]"  :disabled="item=='id'"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible1 = false">取 消</el-button>
    <el-button type="primary" @click="putone">确 定</el-button>
  </div>
</el-dialog>

     <!-- 修改一条 -->
 <el-dialog title="修改一条" :visible.sync="dialogFormVisible1">
  <el-form>
    <el-form-item v-for='item in this.keylist' :key='item' :label="item" :label-width="formLabelWidth">
      <el-input  v-model="indexitem[item]"  :disabled="item=='id'"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="putone2">取 消</el-button>
    <el-button type="primary" @click="putone1">确 定</el-button>
  </div>
</el-dialog>

  </div>
</template>

<script>
import toExcel from './excel/Export2Excel'

export default {
  name: 'app',
  data(){
    return { 
      indexitem:{},
      listdata:[],
      fileData:[],
      studentlist:[],
      keylist:[],
      currentPage4: 1,
      total:0,
      page:2,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      form: {},
      formLabelWidth: '120px',
     
    }
  },
  components: {

  },
  methods:{
    //取消提交
    putone2(){
      let index=JSON.parse(sessionStorage.getItem('itemone'))['id']
      this.studentlist.splice(index-1,1,JSON.parse(sessionStorage.getItem('itemone')))
      this.pagelist()
      this.dialogFormVisible1=false
    },
    //确定修改提交
    putone1(){
      this.dialogFormVisible1=false
    },
    
    //新添加一条
    putone(){
      let id=this.studentlist.length+1
      this.form['id']=id
      this.studentlist.push(this.form)
      this.refnew()
      this.form={}
      // this.pagelist()
      this.dialogFormVisible=false
    },

    //页面刷新
    refnew(){
      this.total=this.studentlist.length
      },

      //关于页码的控制
         handleSizeChange(val) {
         this.page=val
         this.pagelist()
      },
      handleCurrentChange(val) {
        this.currentPage4=val
        this.pagelist()
      },

//编辑和删除
       handleEdit(index, row) {
        // console.log(index, row);
        this.dialogFormVisible1=true
        this.indexitem=row
        // console.log(row)
        sessionStorage.setItem('itemone',JSON.stringify(row))
      },


      handleDelete(index, row) {
         this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           let index1=row['id']
       
       let index2=this.studentlist.findIndex(item=>{
         return item['id']==index1
       })
      //  console.log(index2)
       this.studentlist.splice(index2,1)
       this.total=this.studentlist.length
       this.pagelist() 
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
      },
    // ----------以下为导入Excel数据功能--------------
    // 文件选择回调
    onChange(file) {
      // console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },

    //当前显示页
    pagelist(){  
      var arr1=[]
      var num=0
      if(this.page*this.currentPage4>this.total){
            num=this.total
          }else{
            num=this.page*this.currentPage4
          }
          
      for(let i=this.page*(this.currentPage4-1);i<num;i++){
            arr1.push(this.studentlist[i])
         }
      this.listdata=arr1
    },

    // 读取数据
    readExcel(e) {
      // console.log(e);
      let that = this;
      const files = that.fileData;
      // console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = this.XLSX.read(data, {
            type: "binary"
          });
          if (workbook.SheetNames.length >= 1) {
            this.$message({
              message: "导入数据表格成功",
              showClose: true,
              type: "success"
            });
            this.$message.success("导入成功")
          }
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          this.keylist = Object.keys(ws[0]); 
          this.total=ws.length
        
          this.studentlist=ws
          this.pagelist()
          
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },

    //导出this.keylist
    exportToExcel(){
      const th = this.keylist
      const filterVal = this.keylist
      const data = this.studentlist.map(v => filterVal.map(k => v[k]))
      const [fileName, fileType, sheetName] = ['测试下载', 'xlsx', '测试页']
      toExcel({th, data, fileName, fileType, sheetName})    
    }
  }
}
</script>

<style lang="less" scoped>
  #app{
    max-width: 100vw;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  .header{
    margin-top: 50px;
    width: 60%;
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 50px;
  }
  .container{
    margin-top: 20px;
    width: 80%;
    height: calc(100vh-50px);
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .el-pagination{
      margin-top: 15px;
    }
    .el-table{
     .el-table-column{
       
     } 
    }
  }
}

</style>
